I'm writing a code which will hide my navbar on scroll and display it again accordingly.
So far it works well, but I was curious on how implement some animation or transition to reveal/hide that element.
Here's my code so far
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("bottom-navigation").style.bottom = "0";
} else {
document.getElementById("bottom-navigation").style.bottom = "-100px";
}
prevScrollpos = currentScrollPos;
}
transform and transition which (in contrast to other properties like bottom top etc) can be GPU accelerated.hidden or .hide
than, all you need in JavaScript is a Element.classList.toggle(className, boolean) to toggle that classon(eventname)- unless you're creating brand new elements from in-memory.on* will override any previously added eventname to that element. Use a cumulative approach instead, by using Element.addEventListener()const EL_bottomNav = document.querySelector("#bottom-navigation");
let prevScrollpos = window.pageYOffset;
const toggleBottomNav = () => {
EL_bottomNav.classList.toggle("hide", prevScrollpos <= window.pageYOffset);
prevScrollpos = window.pageYOffset;
};
// Do immediately:
// toggleBottomNav();
// And on page scroll:
window.addEventListener("scroll", toggleBottomNav);
/* QuickReset */ * {margin:0; box-sizing: border-box; }
body {
min-height: 300vh; /* just to force some scrollbars */
}
#bottom-navigation {
position: fixed;
width: 100%;
bottom:0;
background: gold;
padding: 30px;
transition: 0.5s;
}
#bottom-navigation.hide {
transform: translateY(100%);
}
Scroll down and than up
<footer id="bottom-navigation">I'm the bottom nav!</footer>
Nota bene:
Since Events added on scroll are expensive, don't query the DOM for your Element. Cache it beforehand instead (like in the example above). Also a throttle function would be helpful to leverage the load of function calls passed to the event loop in main thread.